package com.scanner.demo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by neo on 2017/12/7.
 */

public class BarCodeReceiver extends BroadcastReceiver {

    private static final String ACTION = "com.barcode.sendBroadcast";
    private static final String DATA = "BARCODE";

    private IReceiverListener listener;

    public void setReceiverListener(IReceiverListener listener) {
        this.listener = listener;
    }

    public static void register(Context context, BroadcastReceiver receiver) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION);
        context.registerReceiver(receiver, filter);
    }

    public static void unregister(Context context, BroadcastReceiver receiver) {
        context.unregisterReceiver(receiver);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null || !ACTION.equals(intent.getAction())) {
            Toast.makeText(context, "无效广播", Toast.LENGTH_SHORT).show();
        } else {
            String dataString = intent.getStringExtra(DATA);
            Log.d("duanfangbiao", "  dataString: " + dataString);
            if (listener != null) {
                listener.onReceive(dataString);
            }
        }
    }


    public interface IReceiverListener {
        void onReceive(String data);
    }


}
